package com.cloudbroker.bcs.platform.dav.middle.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.util.MD5Util;
import com.cloudbroker.bcs.common.util.StringUtil;

public class LiveUtil {
    
    public static Integer getLiveFlag(String roomId, String userId, String salt) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("roomid", roomId);
        params.put("userid", userId);
        String resultMap = LiveUtil.callCCLiveApi("http://api.csslcloud.net/api/room/search",params,salt);

        JSONObject result = JSON.parseObject(resultMap);
        String liveRoomStr = result.getString("room");
        Integer liveFlag = 0;
        if (!StringUtil.isBlank(liveRoomStr)) {
            JSONObject liveRoom = JSON.parseObject(liveRoomStr);
            liveFlag = liveRoom.getInteger("barrage");
        }
        return liveFlag;
    }
    
    /**
     * 功能：将一个Map按照Key字母升序构成一个QueryString. 并且加入时间混淆的hash串
     * @param queryMap query内容
     * @param time 加密时候，为当前时间；解密时，为从querystring得到的时间；
     * @param salt 加密salt
     * @return
     */
    public static String createHashedQueryString(Map<String, String> queryMap, long time, String salt) {
        
        Map<String, String> map = new TreeMap<String, String>(queryMap);
        String qs = createQueryString(map); //生成queryString方法可自己编写
        if (qs == null) {
            return null;
        }
        time = time / 1000;
        String hash = MD5Util.encrypt(String.format("%s&time=%d&salt=%s", qs, time, salt));
        hash = hash.toLowerCase();
        String thqs = String.format("%s&time=%d&hash=%s", qs, time, hash);
        
        return thqs;
    }
    
    private static String createQueryString(Map<String, String> map){
        StringBuilder sb = new StringBuilder();
        for (Entry<String, String> entry : map.entrySet()) {
            sb.append(entry.getKey());
            sb.append('=');
            sb.append(String.valueOf(entry.getValue()));
            sb.append('&');
        }
        String str = sb.toString();
        if (StringUtil.isBlank(str)) {
            return null;
        }
        return str.substring(0, str.length() - 1);
    }
    /*
    * 调用一个LIVE api
    *  @result 返回一个json 字符串
    */
    public static String callCCLiveApi(String url,Map<String,String>params,String salt)
    {
        String urlParam = LiveUtil.createHashedQueryString(params, System.currentTimeMillis(), salt);
        String resultMap = HttpUtil.doGet(url + "?" + urlParam, new HashMap<String, Object>());
        return resultMap;
    }
}
